<?php
// 课室信息展示页面 - 详细版
// 文件：/workspace/rooms_display_detail.php

// 启用错误显示用于调试
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户登录
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// 页面标题
$page_title = "课室详细信息展示";

// 数据库连接
require_once 'database.php';

// 数据库连接检查
$db_connected = true;
try {
    if (!$conn) {
        throw new Exception("数据库连接失败");
    }
    // 测试连接
    $conn->query("SELECT 1");
} catch (Exception $e) {
    error_log("数据库连接错误: " . $e->getMessage());
    $db_connected = false;
}

if (!$db_connected) {
    $_SESSION['error_message'] = "数据库连接失败，请联系管理员";
    header('Location: user_home.php');
    exit();
}

// 处理删除课室请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_room'])) {
    try {
        $room_id = intval($_POST['room_id']);

        $delete_sql = "DELETE FROM examination_rooms WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param('i', $room_id);

        if ($delete_stmt->execute()) {
            $success_message = "课室 " . $_POST['room_number'] . " 已成功删除";
        } else {
            $error_message = "删除失败，请重试";
        }
    } catch (Exception $e) {
        $error_message = "删除失败: " . $e->getMessage();
    }
}

// 获取所有课室信息，按楼栋和楼层分组
$rooms_sql = "SELECT * FROM examination_rooms ORDER BY building_number DESC, floor_number, room_number";
$rooms_result = $conn->query($rooms_sql);

$rooms_by_building = [];
$total_rooms = 0;

if ($rooms_result) {
    while ($room = $rooms_result->fetch_assoc()) {
        // 使用building_number和floor_number字段进行分组
        $building = $room['building_number'] ?? 1;
        $floor = $room['floor_number'] ?? 1;

        if (!isset($rooms_by_building[$building])) {
            $rooms_by_building[$building] = [];
        }
        if (!isset($rooms_by_building[$building][$floor])) {
            $rooms_by_building[$building][$floor] = [];
        }

        $rooms_by_building[$building][$floor][] = $room;
        $total_rooms++;
    }
}

// 统计信息
$building_stats = [];
foreach ($rooms_by_building as $building => $floors) {
    $building_total = 0;
    foreach ($floors as $floor_rooms) {
        $building_total += count($floor_rooms);
    }
    $building_stats[$building] = $building_total;
}

// 颜色映射函数
function getRoomHeaderColor($purpose, $room_type) {
    if ($purpose !== '考场') {
        return '#6c757d'; // Gray
    } else {
        switch ($room_type) {
            case '学生课室': return '#0d6efd'; // Blue
            case '实训室': return '#ffc107';   // Yellow
            case '电脑机房': return '#198754'; // Green
            default: return '#6c757d';        // Gray fallback
        }
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- 统一样式 -->
    <link rel="stylesheet" href="css/unified-style.css">

    <style>
        .room-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }

        .room-card {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
            transition: all 0.3s ease;
            opacity: 1;
            transform: translateY(0px);
        }

        .room-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .room-header {
            color: white;
            padding: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .room-number {
            font-size: 18px;
            font-weight: 600;
        }

        .room-info {
            padding: 15px;
        }

        .room-info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }

        .room-actions {
            padding: 15px;
            background: #f8f9fa;
            display: flex;
            gap: 10px;
            justify-content: flex-end;
        }

        .building-section {
            margin-bottom: 40px;
        }

        .building-title {
            color: #1f2937;
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #0d6efd;
        }

        .floor-section {
            margin-bottom: 30px;
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #0d6efd;
        }

        .floor-title {
            color: #495057;
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 15px;
        }

        .enhancement-notice {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #155724;
        }

        .enhancement-notice .badge {
            background: #28a745;
            color: white;
            margin-right: 5px;
        }

        .purpose-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            margin-left: 5px;
        }

        .purpose-exam { background: #d4edda; color: #155724; }
        .purpose-backup { background: #fff3cd; color: #856404; }
        .purpose-office { background: #cce5ff; color: #004085; }
        .purpose-reception { background: #e2e3e5; color: #383d41; }
        .purpose-broadcast { background: #f8d7da; color: #721c24; }
        .purpose-medical { background: #ffeaa7; color: #6c5ce7; }
        .purpose-teacher-office { background: #e1f5fe; color: #01579b; }
    </style>
</head>
<body>
<!-- 导航栏 -->
<?php include_once 'common/navigation.php'; ?>

<!-- 主要内容 -->
<div class="container main-content">
    <!-- 页面标题 -->
    <div class="card">
        <div class="page-header">
            <h1 class="page-title">课室详细信息展示</h1>
            <p class="page-subtitle">查看所有课室的详细信息，包括管理员、用途、归属等完整数据</p>
        </div>
    </div>

    <!-- 功能增强通知 -->
    <div class="enhancement-notice">
        <h6><i class="fas fa-info-circle"></i> 详细信息视图</h6>
        <p class="mb-0">
            <span class="badge">DETAIL</span>
            显示课室的完整详细信息，包括容量、管理员、用途、归属权等。如需查看课室整体布局，请点击"显示课室整体布局"按钮。
        </p>
    </div>

    <!-- 消息提示 -->
    <?php if (isset($success_message)): ?>
        <div class="alert alert-success fade-in">
            <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
        </div>
    <?php elseif (isset($error_message)): ?>
        <div class="alert alert-danger fade-in">
            <i class="fas fa-exclamation-triangle"></i> <?php echo htmlspecialchars($error_message); ?>
        </div>
    <?php endif; ?>

    <!-- 统计概览 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-chart-bar"></i> 课室统计概览
            <div class="d-flex gap-2 ms-auto">
                <a href="rooms_display.php" class="btn btn-info">
                    <i class="fas fa-table"></i> 显示课室整体布局
                </a>
                <a href="add_room.php" class="btn btn-warning">
                    <i class="fas fa-plus"></i> 添加新课室
                </a>
            </div>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3">
                    <div class="info-item">
                            <span class="info-label">
                                <i class="fas fa-building text-primary"></i> 总课室数
                            </span>
                        <span class="info-value"><?php echo $total_rooms; ?></span>
                    </div>
                </div>
                <?php foreach ($building_stats as $building => $count): ?>
                    <div class="col-md-3">
                        <div class="info-item">
                                <span class="info-label">
                                    <i class="fas fa-home text-info"></i> <?php echo $building; ?>号楼
                                </span>
                            <span class="info-value"><?php echo $count; ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- 课室信息展示 -->
    <?php if (!empty($rooms_by_building)): ?>
        <?php foreach ($rooms_by_building as $building => $floors): ?>
            <div class="building-section">
                <h2 class="building-title">
                    <i class="fas fa-building"></i> <?php echo $building; ?>号楼
                    <small class="text-muted">(<?php echo $building_stats[$building]; ?>间课室)</small>
                </h2>

                <?php
                // 高楼层在上方，低楼层在下方
                krsort($floors);
                foreach ($floors as $floor => $floor_rooms):
                    ?>
                    <div class="floor-section">
                        <h3 class="floor-title">
                            <i class="fas fa-layer-group"></i>
                            <?php
                            if ($floor == -1) {
                                echo '地下一楼';
                            } else {
                                echo '第' . $floor . '层';
                            }
                            ?>
                            <small class="text-muted">(<?php echo count($floor_rooms); ?>间)</small>
                        </h3>

                        <div class="room-grid">
                            <?php foreach ($floor_rooms as $room): ?>
                                <?php
                                $purpose = $room['purpose'] ?? '考场';
                                $room_type = $room['room_type'] ?? '未分类';
                                $header_color = getRoomHeaderColor($purpose, $room_type);
                                ?>
                                <div class="room-card">
                                    <div class="room-header" style="background-color: <?php echo $header_color; ?>">
                                        <div class="room-number"><?php echo htmlspecialchars($room['room_number']); ?></div>
                                    </div>

                                    <div class="room-info">
                                        <div class="room-info-item">
                                            <span><i class="fas fa-users"></i> 容量：</span>
                                            <span><?php echo $room['capacity'] ?? 30; ?>人</span>
                                        </div>
                                        <div class="room-info-item">
                                            <span><i class="fas fa-building"></i> 楼栋：</span>
                                            <span><?php echo $room['building'] ?? $building . '号楼'; ?></span>
                                        </div>
                                        <div class="room-info-item">
                                            <span><i class="fas fa-layer-group"></i> 楼层：</span>
                                            <span><?php echo $room['floor'] ?? '第' . $floor . '层'; ?></span>
                                        </div>
                                        <?php if (!empty($room['sub_building'])): ?>
                                            <div class="room-info-item">
                                                <span><i class="fas fa-map-marker-alt"></i> 区域：</span>
                                                <span><?php echo htmlspecialchars($room['sub_building']); ?>座</span>
                                            </div>
                                        <?php endif; ?>
                                        <div class="room-info-item">
                                            <span><i class="fas fa-user-tie"></i> 管理员：</span>
                                            <span><?php echo htmlspecialchars($room['administrator_name'] ?? '待填写'); ?></span>
                                        </div>
                                        <div class="room-info-item">
                                            <span><i class="fas fa-clipboard-list"></i> 用途：</span>
                                            <span><?php echo htmlspecialchars($purpose); ?></span>
                                        </div>
                                        <div class="room-info-item">
                                            <span><i class="fas fa-certificate"></i> 归属：</span>
                                            <span><?php echo htmlspecialchars($room['ownership'] ?? '华材'); ?></span>
                                        </div>
                                        <?php if (!empty($room['address'])): ?>
                                            <div class="room-info-item">
                                                <span><i class="fas fa-map-pin"></i> 地址：</span>
                                                <span><?php echo htmlspecialchars($room['address']); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    </div>

                                    <div class="room-actions">
                                        <button onclick="editRoom(<?php echo $room['id']; ?>, '<?php echo htmlspecialchars($room['room_number']); ?>')"
                                                class="btn btn-info btn-sm">
                                            <i class="fas fa-edit"></i> 编辑
                                        </button>
                                        <form method="post" style="display: inline;"
                                              onsubmit="return confirm('确定要删除课室 <?php echo htmlspecialchars($room['room_number']); ?> 吗？')">
                                            <input type="hidden" name="room_id" value="<?php echo $room['id']; ?>">
                                            <input type="hidden" name="room_number" value="<?php echo htmlspecialchars($room['room_number']); ?>">
                                            <button type="submit" name="delete_room" class="btn btn-danger btn-sm">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    <?php else: ?>
        <div class="card">
            <div class="card-body">
                <div class="text-center py-5">
                    <div class="mb-3">
                        <i class="fas fa-building" style="font-size: 48px; color: #6c757d;"></i>
                    </div>
                    <h4 class="text-muted">暂无课室信息</h4>
                    <p class="text-muted">还没有添加任何课室</p>
                    <a href="add_room.php" class="btn btn-warning">
                        <i class="fas fa-plus"></i> 添加第一个课室
                    </a>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
    // 编辑课室
    function editRoom(roomId, roomNumber) {
        window.location.href = 'edit_room.php?id=' + roomId;
    }

    // 页面加载动画
    document.addEventListener('DOMContentLoaded', function() {
        const roomCards = document.querySelectorAll('.room-card');

        roomCards.forEach((card, index) => {
            card.style.opacity = '0';
            card.style.transform = 'translateY(20px)';

            setTimeout(() => {
                card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                card.style.opacity = '1';
                card.style.transform = 'translateY(0)';
            }, index * 50);
        });
    });

    // 搜索功能
    function searchRooms() {
        const searchTerm = prompt('请输入要搜索的课室号:');
        if (searchTerm) {
            const roomCards = document.querySelectorAll('.room-card');
            let found = false;

            roomCards.forEach(card => {
                const roomNumber = card.querySelector('.room-number').textContent;
                if (roomNumber.includes(searchTerm)) {
                    card.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    card.style.border = '2px solid #0d6efd';
                    setTimeout(() => {
                        card.style.border = '1px solid #e9ecef';
                    }, 3000);
                    found = true;
                }
            });

            if (!found) {
                alert('未找到包含 "' + searchTerm + '" 的课室');
            }
        }
    }
</script>

<?php
// 关闭数据库连接
if (isset($conn)) {
    $conn->close();
}
?>
</body>
</html>